/**
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * 本软件及相关文档文件（以下简称“软件”）的版权归 铭软科技 所有
 * 遵循铭软科技《保密协议》
 */

package net.mingsoft.mwebsite.action;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.biz.IManagerBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.mdiy.biz.IDictBiz;
import net.mingsoft.mwebsite.biz.IWebsiteBiz;
import net.mingsoft.mwebsite.entity.WebsiteEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 网站基本信息控制层
 * @author 铭软团队
 * @version
 * 版本号：100-000-000<br/>
 * 创建日期：2014-07-14<br/>
 * 历史修订：2017-3-20 bootstrap-table列表更改<br/>
 */
@Api(value = "网站基本信息接口")
@Controller
@RequestMapping("/${ms.manager.path}/website")
public class WebsiteAction extends BaseAction {

	/**
	 * appBiz业务层的注入
	 */
	@Autowired
	private IWebsiteBiz websiteBiz;

	@Value("ms.upload.template")
	private String template;

	/**
	 * managerBiz业务层的注入
	 */
	@Autowired
	private IManagerBiz managerBiz;

	/**
	 * managerBiz业务层的注入
	 */
	@Autowired
	private IDictBiz dictBiz;

	/**
	 * 返回站点管理页面
	 * @param request
	 * @param mode
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "主界面")
	@GetMapping("/index")
	public String index(HttpServletRequest request,@ApiIgnore ModelMap mode,HttpServletResponse response){
		return "/mwebsite/index";
	}
	/**
	 * 查询站点列表信息
	 * @param request 请求对象
	 * @param response 响应对象
	 * @return 站点列表数据
	 */
	@ApiOperation(value = "查询站点列表信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "websiteName", value = "应用名称", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteStyle", value = "网站采用的模板风格", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteKeyword", value = "网站关键字", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteUrl", value = "网站域名", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteState", value = "网站状态 0:运行中 1:停止", required = false,paramType="query"),
	})
	@GetMapping("/list")
	@ResponseBody
	public ResultData list(@ModelAttribute @ApiIgnore WebsiteEntity websiteEntity, HttpServletRequest request, HttpServletResponse response){
		BasicUtil.startPage();
		List<WebsiteEntity> websiteList = websiteBiz.query(websiteEntity);
		EUListBean _list = new EUListBean(websiteList, (int) BasicUtil.endPage(websiteList).getTotal());
		return ResultData.build().success(_list);
	}

	/**
	 * 根据id删除站点信息
	 * @param appId 要删除的站点Id
	 * @param request 请求对象
	 * @return 返回当前页数
	 */
	@ApiOperation(value = "批量id删除站点信息")
	@ApiImplicitParam(name = "appId", value = "要删除的站点Id", required = false,paramType="path")
	@GetMapping("/{appId}/delete")
	@ResponseBody
	public ResultData delete(@PathVariable int appId, HttpServletRequest request){
		WebsiteEntity website = websiteBiz.getOne(Wrappers.<WebsiteEntity>lambdaQuery().eq(WebsiteEntity::getWebsiteId, appId));
		/*
		 * 删除对应的站点管理员
		 */
		if(website!=null){
            ManagerEntity managerEntity = websiteBiz.getManageByAppId(website.getWebsiteId());
            managerBiz.deleteEntity(managerEntity);
			websiteBiz.deleteEntity(appId);
		}
		return ResultData.build().success();
	}


	@ApiOperation(value = "批量id删除站点信息")
	@ApiImplicitParam(name = "websiteIds", value = "站点编号，多个以逗号隔开", required = true,paramType="query")
	@LogAnn(title = "批量id删除站点信息",businessType= BusinessTypeEnum.DELETE)
	@GetMapping("/batchDelete")
	@ResponseBody
	public ResultData batchDelete(HttpServletRequest request, HttpServletResponse response){
		int[] ids = BasicUtil.getInts("websiteIds", ",");
		Arrays.stream(ids).forEach(id->{
			websiteBiz.deleteEntity(id);
		});
		return ResultData.build().success();
	}

	/**
	 * 跳转到站点保存页面
	 * @param request 请求对象
	 * @param mode ModelMap实体对象
	 * @return 站点保存页面
	 */
	@GetMapping("/add")
	public String add(HttpServletRequest request,@ApiIgnore ModelMap mode){
		//超级管理员识别
		mode.addAttribute("SystemManager",true);
		WebsiteEntity website = new WebsiteEntity();
		//传入一个空的app
		mode.addAttribute("website",website);
		//设置接口请求路径
		mode.addAttribute("autoCURD", "save");
		return "/mwebsite/website_form";
	}

	/**
	 * 跳转到修改页面
	 * @param websiteId 站点id
	 * @return 站点修改页面
	 */
	@GetMapping(value="/{websiteId}/edit")
	public String edit(@PathVariable int websiteId) {
		return "/mwebsite/website_form";
	}


	/**
	 * 获取站点信息
	 * @param websiteId
	 * @param request
	 * @return
	 */
	@GetMapping(value="/{websiteId}/get")
	@ResponseBody
	public ResultData get(@ApiIgnore @PathVariable int websiteId, HttpServletRequest request) {
		WebsiteEntity website = null;
		if (websiteId<0) {
			website = this.getWebsite(request);
		} else {
			website = websiteBiz.getOne(Wrappers.<WebsiteEntity>lambdaQuery().eq(WebsiteEntity::getWebsiteId, websiteId));
		}
		return ResultData.build().success(website);
	}

	@ApiOperation(value = "更新站点信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "websiteId", value = "应用编号", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteName", value = "应用名称", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteDescription", value = "应用描述", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteLogo", value = "应用logo", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteStyle", value = "网站采用的模板风格", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteKeyword", value = "网站关键字", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteCopyright", value = "网站版权信息", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteUrl", value = "网站域名", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteDatetime", value = "站点日期", required = false,paramType="query"),
			@ApiImplicitParam(name = "websitePayDate", value = "应用续费时间", required = false,paramType="query"),
			@ApiImplicitParam(name = "websitePay", value = "应用费用清单", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteState", value = "网站状态 0:运行中 1:停止", required = false,paramType="query"),
	})
	@LogAnn(title = "更新站点信息",businessType= BusinessTypeEnum.UPDATE)
	@PostMapping("/update")
	@ResponseBody
	public ResultData update(@ModelAttribute @ApiIgnore WebsiteEntity website,@ApiIgnore ModelMap mode,  HttpServletRequest request, HttpServletResponse response){
		mode.clear();
		// 获取Session值
		ManagerEntity managerSession = (ManagerEntity) getManagerBySession();
		if(managerSession==null){
			return ResultData.build().error();
		}

		//验证重复
		if(super.validated("app", "app_dir", website.getWebsiteDir(), String.valueOf(website.getWebsiteId()), "id")){
			return ResultData.build().error(getResString("err.exist", this.getResString("app.dir")));
		}
		//验证网站生成目录的值是否合法
		if(StringUtils.isBlank(website.getWebsiteDir())){
			return ResultData.build().error(getResString("err.empty", this.getResString("app.dir")));
		}
		if(!StringUtil.checkLength(website.getWebsiteDir()+"", 0, 10)){
			return ResultData.build().error(getResString("err.length", this.getResString("app.dir"), "0", "10"));
		}
		mode.addAttribute("managerSession",managerSession);

		int roleId = managerSession.getRoleId();
		//判断站点数据的合法性
		// 获取cookie
//		String cookie =this.getCookie(request, CookieConstEnum.PAGENO_COOKIE);
		if(!checkForm(website,response)){
			return ResultData.build().error();
		}
		if(StringUtils.isNotEmpty(website.getWebsiteLogo())) {
			website.setWebsiteLogo( website.getWebsiteLogo().replace("|", ""));
		}
		website.setWebsiteUrl(StrUtil.removeSuffix(website.getWebsiteUrl(),"\n"));
		//更新站点信息
		websiteBiz.updateById(website);
		return ResultData.build().success(String.valueOf(roleId));
	}

	@ApiOperation(value = "保存站点信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "websiteName", value = "应用名称", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteDescription", value = "应用描述", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteLogo", value = "应用logo", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteStyle", value = "网站采用的模板风格", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteKeyword", value = "网站关键字", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteCopyright", value = "网站版权信息", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteUrl", value = "网站域名", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteDatetime", value = "站点日期", required = false,paramType="query"),
			@ApiImplicitParam(name = "websitePayDate", value = "应用续费时间", required = false,paramType="query"),
			@ApiImplicitParam(name = "websitePay", value = "应用费用清单", required = false,paramType="query"),
			@ApiImplicitParam(name = "websiteState", value = "网站状态 0:运行中 1:停止", required = false,paramType="query"),
	})
	@LogAnn(title = "保存站点信息",businessType= BusinessTypeEnum.INSERT)
	@PostMapping("/save")
	@ResponseBody
	public ResultData save(@ModelAttribute @ApiIgnore WebsiteEntity website, HttpServletRequest request, HttpServletResponse response){
		//验证站点数据的合法性
		if(!checkForm(website,response)){
			return ResultData.build().error();
		}
		if(super.validated("app", "app_dir", website.getWebsiteDir())){
			return ResultData.build().error(getResString("err.exist", this.getResString("app.dir")));
		}
		//验证网站生成目录的值是否合法
		if(StringUtils.isBlank(website.getWebsiteDir())){
			return ResultData.build().error(getResString("err.empty", this.getResString("app.dir")));
		}
		if(!StringUtil.checkLength(website.getWebsiteDir()+"", 0, 10)){
			return ResultData.build().error(getResString("err.length", this.getResString("app.dir"), "0", "10"));
		}
		//问题:由于上传的图片路径后面可能带有｜符合。所以要进行将“｜”替换空
		//空值判断
		if(StringUtils.isNotEmpty(website.getWebsiteLogo())) {
			website.setWebsiteLogo( website.getWebsiteLogo().replace("|", ""));
		}
		//问题:去掉域名后面的"/"
		//String appUrl = website.getWebsiteHostUrl();
		//website.setWebsiteUrl(appUrl);
		website.setWebsiteUrl(StrUtil.removeSuffix(website.getWebsiteUrl(),"\n"));
		websiteBiz.saveEntity(website);
		return ResultData.build().success();
	}

	/**
	 * 判断站点域名的合法性
	 * @param website 要验证的站点信息
	 * @param response response对象
	 */
	public boolean checkForm(WebsiteEntity website, HttpServletResponse response){
		/*
		 * 判断数据的合法性
		 */
		if(!(StringUtils.isBlank(website.getWebsiteKeyword())) && !StringUtil.checkLength(website.getWebsiteKeyword(), 0,1000)){
			ResultData.build().error(getResString("err.length",this.getResString("website.keyword",net.mingsoft.mwebsite.constant.Const.RESOURCES),"0","1000"));
			return false;
		}
		if(!(StringUtils.isBlank(website.getWebsiteCopyright())) && !StringUtil.checkLength(website.getWebsiteCopyright(), 0,1000)){
			ResultData.build().error(getResString("err.length",this.getResString("website.copyright",net.mingsoft.mwebsite.constant.Const.RESOURCES),"0","1000"));
			return false;
		}
		if(!(StringUtils.isBlank(website.getWebsiteDescription())) && !StringUtil.checkLength(website.getWebsiteDescription(), 0,1000)){
			ResultData.build().error(getResString("err.length",this.getResString("website.descrip",net.mingsoft.mwebsite.constant.Const.RESOURCES),"0","1000"));
			return false;
		}
		if(!StringUtil.checkLength(website.getWebsiteName(),1,50)){
			ResultData.build().error(getResString("err.length",this.getResString("website.title",net.mingsoft.mwebsite.constant.Const.RESOURCES),"1","50"));
			return false;
		}
		if(!(StringUtils.isBlank(website.getWebsiteStyle()))  && !StringUtil.checkLength(website.getWebsiteStyle(),1,30)){
			ResultData.build().error(getResString("err.length",this.getResString("website.style",net.mingsoft.mwebsite.constant.Const.RESOURCES),"1","30"));
			return false;
		}
		if(!StringUtil.checkLength(website.getWebsiteHostUrl(),10,150)){
			ResultData.build().error(getResString("err.length",this.getResString("website.url",net.mingsoft.mwebsite.constant.Const.RESOURCES),"10","150"));
			return false;
		}
		if(!(StringUtils.isBlank(website.getWebsitePay()))  &&  !StringUtil.checkLength(website.getWebsitePay(),0,500)){
			ResultData.build().error(getResString("err.length",this.getResString("website.pay",net.mingsoft.mwebsite.constant.Const.RESOURCES),"0","500"));
			return false;
		}
		return true;
	}

	/**
	 * 判断是否有重复的域名
	 * @param request 请求对象
	 * @return true:重复,false:不重复
	 */
	@ApiOperation(value = "判断是否有重复的域名")
	@ApiImplicitParam(name = "websiteUrl", value = "域名", required = true,paramType="query")
	@GetMapping("/checkUrl")
	@ResponseBody
	public ResultData checkUrl(HttpServletRequest request){
		if(request.getParameter("websiteUrl")!=null){
			if(websiteBiz.countByUrl(request.getParameter("websiteUrl"))>0){
				return ResultData.build().success(true);
			}else{
				return ResultData.build().success(false);
			}
		}else{
			return ResultData.build().success(false);
		}
	}

	@GetMapping("verify")
	@ResponseBody
	public ResultData verify(String fieldName, String fieldValue, String id, String idName){
		boolean verify = false;
		if(StringUtils.isBlank(id)){
			verify = super.validated("app",fieldName,fieldValue);
		}else{
			verify = super.validated("app",fieldName,fieldValue,id,idName);
		}
		if(verify){
			return ResultData.build().success(false);
		}else {
			return ResultData.build().success(true);
		}
	}
}
